const {processDotFlatMode} = require('./dot_mode/flat')
const {processScanFlatMode} = require('./scan_mode/flat')
const {processScanClampMode} = require('./scan_mode/clamp')
const {processDotClampMode} = require('./dot_mode/clamp')
const {processScanRollerMode} = require('./scan_mode/roller')
const {processDotRollerMode} = require('./dot_mode/roller')
const {processPreviewMode} = require('./preview_mode')
const reliefProcess = require('./relief_mode/process');
const config = require('../../config');

function generateGcode(gcode, gCodeDriver, imageData, bitmapData, gcodeParams) {
    if (gcodeParams.previewMode > 0) {
        gCodeDriver.setPreviewMode(true); // 避免发送 m4 指令
        gcodeInitialize(gCodeDriver, gcodeParams); // 程序开始
        processPreviewMode(gCodeDriver, imageData, gcodeParams);
    }else{
        gCodeDriver.annotationBitmap();
        gcodeInitialize(gCodeDriver, gcodeParams); // 程序开始
        switch (gcodeParams.markMode) {
        case 0: // 平面模式
            if (gcodeParams.reliefMode && gcodeParams.reliefMode.enabled){
                reliefProcess({
                    bitmapData: bitmapData,
                    gcodeParams: gcodeParams,
                    gcode: gcode,
                    gCodeDriver: gCodeDriver
                });
            }else{
                if (gcodeParams.bitmapMode < 2) { // 
                    processScanFlatMode(gCodeDriver, imageData, gcodeParams);
                } else {
                    processDotFlatMode(gCodeDriver, imageData, gcodeParams);
                }
            }
            break;
        case 1: // 扩幅模式
            break;   
        case 2: // 旋转模式(夹爪)
            if (gcodeParams.bitmapMode < 2) { // 
                processScanClampMode(gCodeDriver, imageData, gcodeParams);
            } else {
                processDotClampMode(gCodeDriver, imageData, gcodeParams);
            }
            break;
        case 3: // 旋转模式（滚轴）
            if (gcodeParams.bitmapMode < 2) { // 
                processScanRollerMode(gCodeDriver, imageData, gcodeParams);
            } else {
                processDotRollerMode(gCodeDriver, imageData, gcodeParams);
            }
            break;
        default:
            throw new Error(`未知的打标模式: ${gcodeParams.markMode}`);
        }
    }

    gCodeDriver.finishProgram();// 程序结束
}

function gcodeInitialize(gCodeDriver, gcp){
    gCodeDriver.init();
    // 20250808：延迟放在版本号之前
    if (gcp.previewMode === -1 && gcp.bitmapMode >= 2){ // 打点模式
        gCodeDriver.note(`P${gcp.dotTime}S${gcp.laserPowerMaxS}`); // 设置点雕刻时间
    }
    gCodeDriver.feed(gcp.rapidRate * 40);
    gCodeDriver.freq(gcp.frequency);
    gCodeDriver.onLightDelay(gcp.onLightDelay);
    gCodeDriver.offLightDelay(gcp.offLightDelay);
    gCodeDriver.jumpDelay(gcp.jumpDelay);
    gCodeDriver.cornerDelay(gcp.cornerDelay);
    gCodeDriver.version(config.version); 
}

module.exports = { generateGcode };